<template>
  <div>
    <el-dialog :visible="showRoleDialog" title="分配角色" @close="onClose">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="(item, index) in list"
          :key="index"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="small" @click="close">取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handelConfirm"
        >确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      list: [], // 所有角色
      roleIds: [] // 该用户的角色
    }
  },
  async created() {
    const { rows } = await getRoleList({ page: 1, pagesize: 50 })
    this.list = rows
  },
  methods: {
    async getUserDetailById(id) {
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds || []
    },
    onClose() {
      this.close()
    },
    close() {
      this.roleIds = []
      this.$emit('update:show-role-dialog', false)
    },
    async handelConfirm() {
      await assignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('修改角色成功')
      this.close()
    }
  }
}
</script>

<style>
</style>
